<!-- eslint-disable vue/valid-v-slot -->
<template>
    <v-layout>
        <div style="width: 100%;background-color: rgb(239, 239, 239);">
            <div style="margin: 10px;height: 80vh;">
                <v-card height="15%" rounded="lg">
                    <div
                        style="display: flex;align-items: center;height: 100%;padding-left: 2%;justify-content: space-between;">
                        <v-row align="center">
                            <span class="title">课程类别:</span>
                            <el-select size="large" v-model="selectedType" style="width: 150px;"
                                @change="data.currentPage = 1, loadCourseItem({ page: 1, itemsPerPage: data.itemsPerPage })">
                                <el-option v-for="(t, index) in typeList" :key="index" :label="t" :value="t">
                                </el-option>
                            </el-select>
                        </v-row>
                        <v-row style="max-width: 40%;">
                            <div style="margin-right: 2%;">
                                <v-btn variant="tonal" height="38px" color="blue" @click="addItem">添加课程</v-btn>
                            </div>
                            <el-select size="large" v-model="searchType" style="width: 125px;margin-right: 5%;" @change="() => {
                                clearSearch()
                                if (searchType === '全部') loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })
                            }">
                                <el-option v-for="(t, index) in searchList" :key="index" :label="t" :value="t">
                                </el-option>
                            </el-select>
                            <v-text-field variant="outlined" density="compact" style=" max-width: 200px;"
                                prepend-inner-icon="mdi-magnify" placeholder="搜索..." color="blue" v-model="searchInput"
                                :disabled="searchType === '全部'"
                                @change="changeSearch(), loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })"></v-text-field>
                        </v-row>
                    </div>
                </v-card>
                <div style="height:2%;"></div>
                <v-card height="84%" rounded="lg">
                    <v-container style="padding-left: 1%;margin-left: 0;padding-right: 0;">
                        <v-data-table-server :headers="data.headers" :items-length="data.totalItems"
                            :items="data.courseItems" @update:options="loadCourseItem" :loading="data.isLoading"
                            loading-text="加载中..." density="comfortable" no-data-text="表中无数据" height="55vh" fixed-header
                            hover>
                            <template v-slot:top>
                                <v-dialog v-model="isEditing" width="800px">
                                    <v-card>
                                        <v-tabs v-model="tab">
                                            <v-tab value="0">{{ course.isModifying ? '修改课程' : '添加课程' }}</v-tab>
                                            <v-tab value="1" v-if="course.isModifying">安排教师</v-tab>
                                        </v-tabs>
                                        <v-card-text>
                                            <v-window v-model="tab">
                                                <v-window-item value="0">
                                                    <v-container>
                                                        <v-row>
                                                            <v-col>
                                                                <v-text-field variant="outlined" label="课程名称"
                                                                    v-model="course.name"></v-text-field>
                                                            </v-col>
                                                            <div style="width: 10%;"></div>
                                                            <v-col>
                                                                <v-select v-model="course.academy" variant="outlined"
                                                                    :items="academyList" label="开课学院" no-data-text="无数据"
                                                                    item-title="name" item-value="name">
                                                                </v-select>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row>
                                                            <v-col>
                                                                <v-text-field variant="outlined" label="授课教师"
                                                                    v-model="course.teacher" disabled></v-text-field>
                                                            </v-col>
                                                            <div style="width: 10%;"></div>
                                                            <v-col>
                                                                <v-select v-model="course.type" variant="outlined"
                                                                    :items="courseType" item-title="name" item-value="type">
                                                                </v-select>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row>
                                                            <v-col>
                                                                <v-text-field variant="outlined" label="授课地点"
                                                                    v-model="course.location"></v-text-field>
                                                            </v-col>
                                                            <div style="width: 10%;"></div>
                                                            <v-col>
                                                                <v-select v-model="course.selectedTime" chips
                                                                    placeholder="授课时间" variant="outlined" :items="timeList"
                                                                    multiple single-line></v-select>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row>
                                                            <v-col>
                                                                <v-select v-model="course.beginWeek" variant="outlined"
                                                                    :items="weekList" label="起始周">
                                                                </v-select>
                                                            </v-col>
                                                            <div style="width: 10%;"></div>
                                                            <v-col>
                                                                <v-select v-model="course.endWeek" variant="outlined"
                                                                    :items="weekList" label="结束周">
                                                                </v-select>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row>
                                                            <v-col>
                                                                <v-text-field variant="outlined" label="期末占比"
                                                                    v-model="course.finalWeight" type="number"
                                                                    @update:focused="changeWeight(false)">
                                                                </v-text-field>
                                                            </v-col>
                                                            <div style="width: 10%;"></div>
                                                            <v-col>
                                                                <v-text-field variant="outlined" label="预计学分"
                                                                    v-model="course.credit" type="number">
                                                                </v-text-field>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row justify="center">
                                                            <v-col cols="4" align-self="center">
                                                                <v-btn block color="blue" @click="updateCourse"
                                                                    v-if="course.isModifying">
                                                                    修改
                                                                </v-btn>
                                                                <v-btn block color="blue" v-else
                                                                    @click="addCourse">添加</v-btn>
                                                            </v-col>
                                                        </v-row>
                                                    </v-container>
                                                </v-window-item>
                                                <v-window-item value="2">
                                                    <v-container>
                                                        <v-row>
                                                            <v-col>
                                                                <v-text-field variant="outlined" label="课程名称"
                                                                    v-model="course.name" readonly>
                                                                </v-text-field>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row>
                                                            <v-col>
                                                                <v-select v-model="seletedTeacher" variant="outlined"
                                                                    placeholder="选择教师" :items="teacherList"
                                                                    item-title="name" multiple chips item-value="id">
                                                                </v-select>
                                                            </v-col>
                                                        </v-row>
                                                        <v-row justify="center">
                                                            <v-col cols="4" align-self="center">
                                                                <v-btn block color="blue" @click="updateTeacher">确定</v-btn>
                                                            </v-col>
                                                        </v-row>
                                                    </v-container>
                                                </v-window-item>
                                            </v-window>
                                        </v-card-text>
                                    </v-card>
                                </v-dialog>
                            </template>
                            <template v-slot:item="{ item }">
                                <tr style="font-size: small;">
                                    <td>{{ item.index }}</td>
                                    <td>{{ item.name }}</td>
                                    <td>{{ item.type }}</td>
                                    <td>{{ item.academy }}</td>
                                    <td>{{ item.teacher }}</td>
                                    <td>{{ item.credit }}</td>
                                    <td>{{ item.location }}</td>
                                    <td>{{ item.formatTime }}</td>
                                    <td>
                                        <v-row>
                                            <v-icon style="cursor: pointer; margin-right: 5px;" @click="editItem(item)">
                                                mdi-pencil
                                            </v-icon>
                                            <v-icon style="cursor: pointer;" @click="deleteCourse(item.id)">
                                                mdi-delete
                                            </v-icon>
                                        </v-row>
                                    </td>
                                </tr>
                            </template>
                            <template v-slot:bottom>
                                <v-container style="margin-top: 1%;">
                                    <v-row justify="end" align="center">
                                        <div
                                            style="width: 35%;display: flex;justify-content: space-around;align-items: center;">
                                            <span>每页条数：</span>
                                            <el-select size="large" style="width: 150px;" v-model="data.itemsPerPage"
                                                @change="data.currentPage = 1, loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })">
                                                <el-option :value="10"></el-option>
                                                <el-option :value="20"></el-option>
                                            </el-select>
                                            <v-btn elevation="0" variant="outlined" :disabled="data.currentPage === 1"
                                                color="grey"
                                                @click="data.currentPage--, loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })">
                                                <v-icon icon="mdi-chevron-left" size="24"></v-icon>
                                            </v-btn>
                                            <v-btn elevation="0" variant="outlined" color="grey"
                                                :disabled="data.courseItems.length < data.itemsPerPage"
                                                @click="data.currentPage++, loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })">
                                                <v-icon icon="mdi-chevron-right" size="24"></v-icon>
                                            </v-btn>
                                        </div>
                                    </v-row>
                                </v-container>
                            </template>
                        </v-data-table-server>
                    </v-container>
                </v-card>
            </div>
        </div>
    </v-layout>
</template>
<script setup lang="ts">
import { GetAcademyList } from '@/controllers/baseController';
import { SearchCourse, DeleteCourse, UpdateCourse, AddCourse, UpdateTeacher } from '@/controllers/courseController';
import { GetUserList } from '@/controllers/subscriberController';
import { message, messageConfirm, notificationSuccess } from '@/utils/message';
import { onMounted } from 'vue';
import { reactive, ref } from 'vue';
const typeList = ['全部', '必修课', '限选课', '任选课']
const courseType = [{ name: '必修', type: 1 }, { name: '限选', type: 2 }, { name: '任选', type: 3 }]
const typeNumberList = [3, 0, 1, 2]
const searchList = ['全部', '课程名称', '教师', '课序号']
const searchType = ref('全部')
let selectedType = ref('全部')
let searchInput = ref('')
let data = reactive({
    headers: [
        { title: '课序号', key: 'index', sortable: false },
        { title: '课程名称', key: 'name', sortable: false },
        { title: '课程类别', key: 'type', sortable: false },
        { title: '开课学院', key: 'academy', sortable: false },
        { title: '授课教师', key: 'teacher', sortable: false },
        { title: '学分', key: 'credit', sortable: false },
        { title: '授课地点', key: 'location', sortable: false },
        { title: '开课时间', key: 'formatTime', sortable: false },
        { title: '操作', key: 'actions', sortable: false }
    ],
    itemsPerPage: 10,
    totalItems: 0,
    currentPage: 1,
    courseItems: [] as any[],
    isLoading: true,
    name: '',
    index: '',
    teacher: ''
})
//更新课程
const timeList = [
    '周一1~2节', '周一3~4节', '周一5~6节', '周一7~8节', '周一9~10节',
    '周二1~2节', '周二3~4节', '周二5~6节', '周二7~8节', '周二9~10节',
    '周三1~2节', '周三3~4节', '周三5~6节', '周三7~8节', '周三9~10节',
    '周四1~2节', '周四3~4节', '周四5~6节', '周四7~8节', '周四9~10节',
    '周五1~2节', '周五3~4节', '周五5~6节', '周五7~8节', '周五9~10节',
    '周六1~2节', '周六3~4节', '周六5~6节', '周六7~8节', '周六9~10节',
    '周日1~2节', '周日3~4节', '周日5~6节', '周日7~8节', '周日9~10节'
]
const weekList = Array.from({ length: 18 }, (_, index) => index + 1)
let isEditing = ref(false)
let tab = ref(1)
let course = reactive({
    id: -1,
    name: '',
    location: '',
    teacher: '',
    credit: 1,
    selectedTime: [] as string[],
    beginWeek: 1,
    endWeek: 18,
    academy: undefined,
    regularWeight: 0.4,
    finalWeight: 0.6,
    type: 1,
    isModifying: false
})
let teacherList = ref([] as { name: string, id: number }[])
let seletedTeacher = ref([] as number[])
let academyList = ref([] as string[])

onMounted(() => {
    init()
})
async function init() {
    try {
        teacherList.value = await GetUserList('1')
        const aList = await GetAcademyList()
        aList.forEach((academy) => {
            academyList.value.push(academy.name)
        })
    }
    catch (err: any) {
        message(err.message, 'error')
    }
}
function changeWeight(isRegular: boolean) {
    if (isRegular) {
        if (course.regularWeight <= 1 && course.regularWeight >= 0) {
            course.finalWeight = Number((1 - course.regularWeight).toFixed(1))
        }
    }
    else {
        if (course.finalWeight <= 1 && course.finalWeight >= 0) {
            course.regularWeight = Number((1 - course.finalWeight).toFixed(1))
        }
    }
}
function pushFormatTime(list: any[]) {
    const week = Array.from({ length: course.endWeek - course.beginWeek + 1 }, (_, index) => course.beginWeek + index);
    course.selectedTime.forEach((time) => {
        let day = Math.floor(timeList.indexOf(time) / 5) + 1
        let order = timeList.indexOf(time) % 5 + 1
        list.push({
            week: week,
            weekday: day,
            order: order
        })
    })
}
function initForm(item: any) {
    course.id = item.id
    course.name = item.name
    course.academy = item.academy
    course.teacher = item.teacher
    course.credit = item.credit
    course.location = item.location
    pushTimeOrder(item.weekday, item.order)
    const week = item.week as number[]
    course.beginWeek = week[0]
    course.endWeek = week[week.length - 1]
    course.finalWeight = item.finalWeight
    course.regularWeight = 1 - item.finalWeight
    course.type = typeList.indexOf(item.type + '课')
}
function pushTimeOrder(weekday: number | number[], order: number | number[]) {
    if (typeof weekday === 'number' && typeof order === 'number') {
        const index = 5 * (weekday - 1) + (order) - 1;
        course.selectedTime.push(timeList[index]);
    } else if (Array.isArray(weekday) && Array.isArray(order)) {
        for (let i = 0; i < weekday.length; i++) {
            const index = 5 * (weekday[i] - 1) + (order[i]) - 1;
            course.selectedTime.push(timeList[index]);
        }
    }
}
function editItem(item: any) {
    clearForm()
    isEditing.value = !isEditing.value
    course.isModifying = true
    initForm(item)
}
function addItem() {
    clearForm()
    isEditing.value = !isEditing.value
}
function clearForm() {
    course.name = ''
    course.academy = undefined
    course.teacher = ''
    course.credit = 1
    course.location = ''
    course.selectedTime.splice(0, course.selectedTime.length)
    course.beginWeek = 1
    course.endWeek = 18
    course.finalWeight = 0.6
    course.regularWeight = 0.4
    course.isModifying = false
    course.type = 1
    tab.value = 0
}
function verifyForm(): boolean {
    if (course.name === '') {
        message('课程名不能为空')
        return false
    }
    if (!course.academy) {
        message('请选择学院')
        return false
    }
    if (course.credit < 0 || Number.isNaN(course.credit)) {
        message('学分不符合规定')
        return false
    }
    if (course.location === '') {
        message('请选择上课教室')
        return false
    }
    if (Number.isNaN(course.finalWeight) || Number.isNaN(course.regularWeight) || (Number(course.regularWeight.toString()) + Number(course.finalWeight.toString()) !== 1)) {
        message('占比不合规定')
        return false
    }
    if (course.beginWeek > course.endWeek) {
        message('请选择正确的上课周数')
        return false
    }
    return true
}
async function updateCourse() {
    if (!verifyForm()) return
    const courseData = {
        id: course.id,
        name: course.name,
        location: course.location,
        credit: course.credit.toString(),
        academy: course.academy,
        finalWeight: Number(course.finalWeight.toString()),
        comment: '',
        courseTimeList: [] as any[],
        type: course.type - 1
    }
    pushFormatTime(courseData.courseTimeList)
    UpdateCourse(courseData).then(
        () => {
            loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })
            notificationSuccess('修改成功', '')
        }
    ).catch(err => message(err.message, 'error'))
}
async function addCourse() {
    if (!verifyForm()) return
    const courseData = {
        id: course.id,
        name: course.name,
        location: course.location,
        credit: course.credit.toString(),
        academy: course.academy,
        finalWeight: Number(course.finalWeight.toString()),
        comment: '',
        courseTimeList: [] as any[],
        type: course.type - 1
    }
    pushFormatTime(courseData.courseTimeList)
    AddCourse(courseData).then(
        () => {
            loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })
            setTimeout(() => {
                isEditing.value = false
            }, 100)
            notificationSuccess('添加成功', '')
        }
    ).catch(err => message(err.message, 'error'))
}
async function updateTeacher() {
    if (seletedTeacher.value.length === 0) {
        message('请选择教师')
        return
    }
    let teacherList = seletedTeacher.value.join(',')
    UpdateTeacher(course.id, teacherList).then(
        () => {
            loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })
            setTimeout(() => {
                isEditing.value = false
            }, 100)
            notificationSuccess('添加成功', '')
        }
    ).catch(err => message(err.message, 'error'))
}
//搜索课程
async function searchCourse({ page, pageSize, type, name, index, teacher }: {
    page: number, pageSize: number, type: number,
    name: string
    index: string
    teacher: string
}) {
    try {
        let courseList = (await SearchCourse({ page, pageSize, type, name, index, teacher })) as any[]
        courseList.forEach(
            (val) => {
                let type = val.type
                val.type = type === 0 ? '必修' : type === 1 ? '限选' : '任选'
            }
        )
        return ({ items: courseList, total: courseList.length })
    }
    catch (error: any) {
        message(error.message, 'error')
    }
}
function loadCourseItem({ page, itemsPerPage }: { page: number; itemsPerPage: number }) {
    data.isLoading = true
    searchCourse({
        page: page, pageSize: itemsPerPage, type: typeNumberList[typeList.indexOf(selectedType.value)],
        name: data.name, index: data.index, teacher: data.teacher
    }).then(
        (result) => {
            if (result) {
                data.courseItems = result.items || []
                data.totalItems = result.total || 0
            }
            data.isLoading = false
        }
    )
}
async function deleteCourse(id: number) {
    messageConfirm('确认删除当前课程吗？')
        .then(() => {
            DeleteCourse(id).then(
                () => {
                    message('删除成功', 'success')
                    loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })
                }
            ).catch(err => message(err.message, 'error'))
        })
        .catch(
            () => { return }
        )
}
function changeSearch() {
    switch (searchType.value) {
        case '课程名称': {
            data.name = searchInput.value
            break
        }
        case '课序号': {
            data.index = searchInput.value
            break
        }
        case '教师': {
            data.teacher = searchInput.value
            break
        }
    }
}
function clearSearch() {
    data.name = ''
    data.index = ''
    data.teacher = ''
    searchInput.value = ''
}
</script>
<style scoped>
.title {
    font-weight: bold;
    font-size: 18px;
    margin-right: 1%;
}
</style>